package com.atguigu.springcloud.exception;

import com.atguigu.springcloud.entity.CommonResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;
import java.util.ArrayList;
import java.util.Optional;

/**
 * @Author lizhilong
 * @create 2020/5/2 14:27
 * @desc
 */

@ControllerAdvice
public class GloableExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult<Object> exceptionHandler(HttpServletRequest request, Throwable  e) {
        CommonResult<Object> commonResult = new CommonResult<>();
        String errorCode;
        String errorMessage;
        if (e instanceof BaseException) {
            BaseException be = (BaseException) e;
            errorCode = be.getErrorCode();
            errorMessage = be.getMessage();
        } else if (e instanceof BindException) {
            errorCode = "999999";
            BindingResult result = ((org.springframework.validation.BindException) e).getBindingResult();
            StringBuilder stringBuilder = new StringBuilder();
            Optional.ofNullable(result.getFieldErrors()).orElse(new ArrayList<>()).forEach(f -> {
                stringBuilder.append(f.getField())
                        .append(" ")
                        .append(f.getDefaultMessage())
                        .append(", 当前值: '")
                        .append(f.getRejectedValue())
                        .append("'; ");
            });

            errorMessage = stringBuilder.toString();
        } else {
            errorCode = "000000";
            errorMessage = "系统错误，正在修复中，请等待";
        }
        commonResult.setCode(errorCode);
        commonResult.setMessage(errorMessage);
        commonResult.setData(null);
        return commonResult;
    }
}
